<?php

namespace app\admin\framework\controller;

use app\admin\framework\api\Permission;
use app\common\model\AdminMenu;
use app\common\model\Role;
use app\common\model\RoleUser;
use app\common\service\UserService;

#[Permission('角色管理', 'Auth')]
class RoleController
{
    private $noNeedAuth = ['menu'];
    
    #[Permission('详情')]
    public function detail()
    {
        $id = request()->get('id', 0);
        $result = Role::find($id)->toArray();
        return apiSuccess(data: $result);
    }
    
    #[Permission('查询')]
    public function select()
    {
        $roles = Role::select();
        return apiSuccess(data: ['list' => $roles]);
    }
    
    #[Permission('创建')]
    public function create()
    {
        if (request()->method() === 'PUT') {
            $data = request()->post();
            (new Role())->save($data);
            return apiSuccess('保存成功');
        }
        return apiError('保存失败');
    }
    
    #[Permission('更新')]
    public function update()
    {
        if (request()->method() === 'PUT') {
            $data = request()->post();
            if ($data['id'] == 1) {
                return apiError("超级管理员角色不能被修改！");
            }
            (new Role())->update($data);
            return apiSuccess('保存成功');
        }
        return apiError('保存失败');
    }
    
    #[Permission('删除')]
    public function delete()
    {
        if (request()->method() === 'DELETE') {
            $id = request()->get("id", 0);
            if ($id == 1) {
                return apiError("超级管理员角色不能被删除！");
            }
            $count = RoleUser::where('role_id', $id)->count();
            if ($count > 0) {
                return apiError("该角色已经有用户！");
            } else {
                if (Role::destroy($id)) {
                    return apiSuccess('删除成功');
                } else {
                    return apiError('删除失败');
                }
            }
        }
        return apiError('非法删除');
    }
    
    #[Permission('操作授权')]
    public function authorize()
    {
        $menus = AdminMenu::getMenus();
        if (request()->method() === 'GET') {
            $id = request()->get('id');
            $role = Role::where('id', $id)->find();
            $checked = [];
            foreach (explode(',', $role['rules']) as $value) {
                foreach ($menus as $v2) {
                    if ($v2['path'] == $value) {
                        $checked[] = $v2['id'];
                    }
                }
            }
            return apiSuccess(data: [
                'menu' => $menus,
                'role' => $role,
                'checked' => $checked
            ]);
        }
        
        if (request()->method() === 'POST') {
            $id = request()->post('id', 0);
            if (!$id) {
                return apiError("需要授权的角色不存在！");
            }
            $checked = request()->post('checked', []);
            $rules = [];
            foreach ($menus as $key => $value) {
                if (array_search($value['id'], $checked) !== false) {
                    $rules[] = $value['path'];
                }
            }
            (new Role())->where('id', $id)->update(['rules' => implode(',', $rules)]);
            return apiSuccess('授权成功');
        }
    }
    
    public function menu()
    {
        
        $rules = UserService::getRules(UserService::getId());
        $menus = AdminMenu::getMenus();
        $ids = [];
        if (!empty($rules) && $rules[0] === '*') {
        
        } else {
            foreach ($rules as $value) {
                $ids = array_merge($ids, getParents($value, $menus));
            }
            $ids = array_unique($ids);
        }
        $list = [];
        foreach ($menus as $value) {
            if ($value['type'] === 1 || $value['type'] === 2) {
                if (!empty($rules) && $rules[0] === '*') {
                    $list[] = $value;
                } else {
                    if (in_array($value['id'], $ids)) {
                        $list[] = $value;
                    }
                }
            }
        }
        
        foreach ($list as $key => $value) {
            $list[$key]['path'] = strtolower($value['path']);
            $list[$key]['name'] = strtolower($value['name']);
            $list[$key]['component'] = strtolower($value['path']);
        }
        
        array_multisort(array_column($list, 'list_order'), SORT_ASC, $list);
        return apiSuccess(data: ['list' => $list]);
    }
    
    
}